package com.heima.kafka.spring.stream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

@Configuration
public class MyKafkaStream {

    @Bean
    public KStream<String,String> kStream(StreamsBuilder streamsBuilder){
        //1指定要监听哪个上游主题,并获取到对应的流
        KStream<String, String> stream = streamsBuilder.stream("topicA");
        //2、对流进行统计
        stream
                .flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    @Override
                    public Iterable<String> apply(String value) {
                        return Arrays.asList(value.split(" "));
                    }
                })
                .groupBy(new KeyValueMapper<String, String, Object>() {
                    @Override
                    public Object apply(String key, String value) {
                        return value;
                    }
                })
                .windowedBy(TimeWindows.of(Duration.ofSeconds(5)))
                .count()
                .toStream()
                .map(new KeyValueMapper<Windowed<Object>, Long, KeyValue<String, String>>() {
                    @Override
                    public KeyValue<String, String> apply(Windowed<Object> key, Long value) {
                        return new KeyValue<>(key.key().toString(),String.valueOf(value));
                    }
                })
                .to("topicB");

        return stream;
    }
}
